// pages/index/index.js
// const THREE = require('../../libs/three')
import * as THREE from '../../libs/three'
import { OrbitControls } from '../../jsm/controls/OrbitControls'
const THREEAR  = require('../../libs/THREEAR')
const w = 300
let h = 200
let dpr = 1
let c2d_freshId = 0
let c2d,c2d_canvasId
let lastTime = 0
let video, videoCtx, ctx1
let scene, camera, renderer, ctx3
let texture, mesh, geometry
let initCanvas = false
let count = 0;
let controls, controller
// let videoFrame = new Uint8Array(2000000);//保存视频的某一帧
let videoFrame = undefined
Page({
  /**
   * 页面的初始数据
   */
  data: {
    videoSrc:'https://www.logitechg.com.cn/content/dam/gaming/en/products/kda/lol-g-kda-2021/lol-kda-hpb.mp4',
    imgSrc:'',
    canvasId:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    // wx.createSelectorQuery()
    //   .select('#c3')
    //   .node()
    //   .exec((res) => {
    //     let canvasId = res[0].node._canvasId
    //     const canvas = THREE.global.registerCanvas(canvasId, res[0].node)
        
    //     this.setData({ canvasId })

    //     const camera = new THREE.PerspectiveCamera(70, canvas.width / canvas.height, 1, 1000);
    //     camera.position.z = 500;
    //     const scene = new THREE.Scene();
    //     scene.background = new THREE.Color(0xAAAAAA);
    //     const renderer = new THREE.WebGLRenderer({ antialias: true });
      
    //     const controls = new OrbitControls(camera, renderer.domElement);
    //     // controls.enableDamping = true;
    //     // controls.dampingFactor = 0.25;
    //     // controls.enableZoom = false;
    //     camera.position.set(200, 200, 500);
    //     controls.update();
    //     const geometry = new THREE.BoxBufferGeometry(200, 200, 200);
      
    //     // const texture = new THREE.TextureLoader().load('./pikachu.png');
    //     // const material = new THREE.MeshBasicMaterial({ map: texture });
    //     const material = new THREE.MeshBasicMaterial()
    //     // const material = new THREE.MeshBasicMaterial({ color: 0x44aa88 });
    //     const mesh = new THREE.Mesh(geometry, material);
    //     scene.add(mesh);
      
    //     // renderer.setPixelRatio(wx.getSystemInfoSync().pixelRatio);
    //     // renderer.setSize(canvas.width, canvas.height);
      
    //     function onWindowResize() {
    //       // camera.aspect = window.innerWidth / window.innerHeight;
    //       // camera.updateProjectionMatrix();
    //       // renderer.setSize(canvas.width, canvas.height);
    //     }
    //     function render() {
    //       canvas.requestAnimationFrame(render);
    //       mesh.rotation.x += 0.005;
    //       mesh.rotation.y += 0.01;
    //       controls.update();
    //       renderer.render(scene, camera);
    //     }

    //     render()

    //   })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let that = this
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    THREE.global.unregisterCanvas(this.data.canvasId)
  },
  loadedmetadata(e){
    let that = this;
    h = w / e.detail.width * e.detail.height

    this.setData({
      h,
    }, () => {
      if(c2d_freshId>0){
        that.cancelAnimationFrame(c2d_freshId)
      }
      that.pushVideoToCanvas(e)
    })
  },
  // 将视频添加至2d画布上用于纹理贴图
  pushVideoToCanvas(e){
    let that = this
    dpr = wx.getSystemInfoSync().pixelRatio
    wx.createSelectorQuery().select("#v").context(res=>{
      video = res.context
      // res.node.width = w * dpr
      // res.node.height = h * dpr
      wx.createSelectorQuery().select("#c2").node(res=>{
        // console.log(res)
        c2d = res.node
        ctx1 = res.node.getContext("2d")
        if(ctx1){
          console.log(ctx1)
          that.getCanvas2dData()
          that._initScene()
        }
        else{
          console.log('视频画布未加载')
          return false
        }
        res.node.height = h * dpr
        res.node.width  = w * dpr
        function drawVideo(){
            c2d_freshId = that.requestAnimationFrame(drawVideo)
            // that.getCanvas2dData()
        }

        // drawVideo()
        // c2d_freshId = that.requestAnimationFrame(function(){
        //   ctx1.drawImage(video, 0, 0, w/dpr, h/dpr );
        // })
      }).exec()
    }).exec();
  },
  //刷新渲染 c2d 画布
  requestAnimationFrame(callback) {

    var currTime = new Date().getTime()

    var timeToCall = Math.max(0, 16.7 - (currTime - lastTime));

    var id = setTimeout(function () {

      callback(currTime + timeToCall)

    }, timeToCall)

    lastTime = currTime + timeToCall

    return id
  },
  cancelAnimationFrame(id) {

    clearTimeout(id)

  },
  _initScene(){
    let that = this
    wx.createSelectorQuery().select("#c3").node(res=>{
      ctx3 = res.node
      let canvasId = res.node._canvasId
      THREE.global.registerCanvas(canvasId, res.node)
      this.setData({ canvasId })
      // scene camera mesh 
      renderer = new THREE.WebGLRenderer({
          antialias: true,
          alpha: true,
          canvas: ctx3,
      });
   
    scene = new THREE.Scene();

    camera = new THREE.PerspectiveCamera(70, ctx3.width / ctx3.height, 1, 1000);
    camera.position.z = 500;
    scene.add(camera);

    controls = new OrbitControls(camera, renderer.domElement);
    // console.log(controls)
        // controls.enableDamping = true;
        // controls.dampingFactor = 0.25;
        // controls.enableZoom = false;
        camera.position.set(200, 200, 500);
      controls.update();

    
    texture = new THREE.DataTexture(videoFrame,w*dpr, h*dpr);
    texture.needsUpdate = true
    texture.minFilter = texture.magFilter = THREE.LinearFilter
    let material = new THREE.MeshBasicMaterial({
        map: texture,
        transparent:true,
        opacity:1
    });

    geometry = new THREE.BoxGeometry(w, h, h);
    // material = new THREE.MeshBasicMaterial()
    mesh = new THREE.Mesh(geometry, material);
    scene.add(mesh);


    // scene.background = new THREE.Color(0xAAAAAA);
    renderer.setPixelRatio( dpr );
    renderer.setSize(w*dpr, h*dpr, false);


    const source = new THREEAR.Source({
      renderer, camera
    })
    let markerGroup = new THREE.Group()
    markerGroup.add(mesh)
    scene.add(markerGroup)
  
    THREEAR.initialize({
      source,
      width: ctx3.width,
      height: ctx3.height
    }).then((_controller) => {
      const patternMarker = new THREEAR.PatternMarker({
        patternUrl:'../../pattern/pattern-cat.patt',
        markerObject: markerGroup
      })

      _controller.trackMarker(patternMarker)
      controller = _controller
      that._render()
    })

    }).exec()
    
    // let init_Int = setInterval(function(){
    //   if(ctx3 && !initCanvas){
    //     that._render()
    //     initCanvas = true
    //     clearInterval(init_Int)
    //   }
    // }, 200)
  },
  //渲染3d画布
  _render() {
    let that = this
    ctx3.requestAnimationFrame(this._render.bind(this))
    // mesh.rotation.y += 0.01;
    that.getCanvas2dData()
    texture.needsUpdate = true;
    renderer.render(scene, camera)
  },
  _render1() {
    let that = this
    ctx3.requestAnimationFrame(this._render.bind(this))
    // mesh.rotation.y += 0.01;
    controls.update();
    renderer.render(scene, camera)
  },
  //获取画布像素数据
  getCanvas2dData(){
    let that = this
    ctx1.drawImage(video, 0, 0, w*dpr, h*dpr);
    let imgData = ctx1.getImageData(0,0,w*dpr, h*dpr)
    let data = new Uint8Array(imgData.data);
    if(videoFrame === undefined){
      videoFrame = new Uint8Array(data.length)
    }
    videoFrame.set(data)
  },
  touchStart(e) {
    console.log('canvas', e)
    THREE.global.touchEventHandlerFactory('canvas', 'touchstart')(e)
  },
  touchMove(e) {
    console.log('canvas', e)
    THREE.global.touchEventHandlerFactory('canvas', 'touchmove')(e)
  },
  touchEnd(e) {
    console.log('canvas', e)
    THREE.global.touchEventHandlerFactory('canvas', 'touchend')(e)
  },
  touchCancel(e) {
    // console.log('canvas', e)
  },
  longTap(e) {
    // console.log('canvas', e)
  },
  tap(e) {
    // console.log('canvas', e)
  },
  documentTouchStart(e) {
    // console.log('document',e)
  },
  documentTouchMove(e) {
    // console.log('document',e)
  },
  documentTouchEnd(e) {
    // console.log('document',e)
  },
  onShareAppMessage(){},
  onShareTimeline(){}

})